<?php
class AuthenticationController 
	extends Zend_Controller_Action 
{
	public function loginAction()
	{
	
		$this->_helper->layout->setLayout('login');
		
		$form = new Web_Form_Login;
		$form->setAction(		
			$this->_helper->url('authenticate')
		);
		
		$this->view->form = $form;
		$this->render('login');
	} 
	
	public function authenticateAction()
	{
		$session = Zend_Registry::get('session');
       
        $form = new Web_Form_Login();
        $request = $this->getRequest();
        
        if (!$form->isValid($request->getPost())) {
            $this->_helper->MyFlashMessenger->addError( "Usuario o clave incorrecta" );
            return $this->_helper->Redirector('login');
        }
        
        $email 	= $request->getParam('email');
        $password	= $request->getParam('password');

        try{
        	$mapper = Vs_Factory::mapper( 'User' );
        	$user = $mapper->authenticate( $email, $password);
        }
        catch (Vs_Exception $e){
        	$this->_helper->MyFlashMessenger->addError( "Usuario o clave incorrecta" );
//        	$this->getHelper('Log')->exception( $e );
            return $this->_helper->Redirector('login');
        
        }        
             
        $session->userId = $user->userId;
        
        $this->_helper->Redirector('index', 'index');        
	}
	
	
	public function logoutAction() 
	{
		$session = Zend_Registry::get('session');
		
		if ( isset($session->userId) ){
			$this->getHelper('ActionLog')->log();
			unset($session->userId);
		}
		
		return $this->_redirect('/');
	}

}
